/****************
 *@description:  商城订单列表   @/orderManage/mallOrder
 *@author: Xhd
 *@API: 
 *@date: 2023-11-13 09:44:38
 *@version: V1.0.0
*************************************************************************/

import React, { useState, useEffect, useRef } from "react";
import { Tabs, Modal, Button, Pagination } from "antd";
import { useNavigate, useLocation } from 'react-router-dom';
import TheQueryForm from '@/components/TheQueryForm';
import Json2Excel from '@/utils/Json2Excel.js';
import { apiGetShopOrderPage, apiGetShopOrderInfoList } from "@/api/orderManage/index.js";
import OrderTable from "./components/goodsTable";
import TheButton from '@/components/TheButton';
import { Decimal } from 'decimal.js';

const StoreBackMallOrder = () => {
  const navigate = useNavigate();
  const queryFormRef = useRef()
  const data = useRef()
  const [searchOption, setSearchOption] = useState([
    { field: 'orderCode', label: '订单编号', placeholder: '请输入订单编号', required: false, rules: [], type: 'Input', defaultValue: '' },
    { field: 'time', label: '下单时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
    { field: 'activityTypeCode', label: '订单类型', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ label: '全部', value: '', }, { label: '普通订单', value: '0' }, { label: '砍价订单', value: '1' }, { label: '拼团订单', value: '2' }, { label: '奖品订单', value: '3' }], defaultValue: '' },
    { field: 'memberId', label: '用户ID', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
    { field: 'memberPhone', label: '收货手机号', placeholder: '请输入', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
    { field: 'goodsQuery', label: '商品ID/名称', placeholder: '支持模糊查询', required: false, rules: [], type: 'Input', defaultValue: '' },
  ])
  const [queryForm, setQueryForm] = useState({})
  const [tabData, setTabData] = useState([
    { key: "", label: '全部' },
    { key: "3", label: '待付款' },
    { key: "6", label: '待分享' },
    { key: "4", label: '待发货' },
    { key: "5", label: '待收货' },
    { key: "9", label: '交易成功' },
    { key: "0", label: '交易关闭' },
  ])
  const [orderState, setOrderState] = useState("")
  const [dataSource, setDataSource] = useState([])
  const [pageData, setPageData] = useState({ pageNo: 1, pageSize: 10 })
  const [total, setTotal] = useState(0)

  useEffect(() => {
    getData(pageData)
  }, [])

  //获取数据
  let getData = async (values) => {
    await apiGetShopOrderPage({ ...values }).then(res => {
      setDataSource(res.data)
      setTotal(res.totalCount)
    })
  }
  //搜索
  let onFormSearch = (values) => {
    if (values && values.hasOwnProperty('time')) {
      values.createTimeStart = values.time[0].format('YYYY-MM-DD') + ' 00:00:00'
      values.createTimeEnd = values.time[1].format('YYYY-MM-DD') + ' 23:59:59'
      delete values.time
    }
    setQueryForm(values)
    setPageData({ pageNo: 1, pageSize: 10 })
    getData({ pageNo: 1, pageSize: 10, orderState, ...values })
  }
  //重置
  let onReset = () => {
    setQueryForm({})
    setPageData({ pageNo: 1, pageSize: 10 })
    getData({ pageNo: 1, pageSize: 10, orderState })
  }
  //tab切换
  let changeKey = (key) => {
    setOrderState(key)
    setPageData({ pageNo: 1, pageSize: 10 })
    getData({ pageNo: 1, pageSize: 10, orderState: key, ...queryForm })
  }
  //翻页
  let pageChange = (pageNo, pageSize) => {
    setPageData({ pageNo, pageSize })
    getData({ pageNo, pageSize, orderState, ...queryForm })
  }
  //导出
  let toExport = async () => {
    if (!queryForm || Object.keys(queryForm).length === 0) {
      Modal.warning({
        title: "提醒",
        content: "请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。",
        okText: "我知道了",
        onOk: () => { }
      })
      return
    }
    await apiGetShopOrderInfoList({ ...queryForm, orderState }).then(res => {
      let data = []
      res.data.forEach(item => {
        let activityTypeCode
          switch (parseInt(item.activityTypeCode)) {
            case 0:
              activityTypeCode = "普通订单";
              break;
            case 1:
              activityTypeCode = "砍价订单";
              break;
            case 2:
              activityTypeCode = "拼团订单";
              break;
            case 3:
              activityTypeCode = "奖品订单";
              break;
            default:
              break;
          }
        data.push({
          orderCode: item.orderCode || '/',
          // storeName: item.storeName || '/',
          buyMemberName: item.buyMemberName || '/',
          orderMemberPhone: item.orderMemberPhone || '/',
          payWay: item.payWay==="Alipay"?"支付宝":item.payWay==="WeChat"?"微信":item.payWay==="UnionPay"?"银联":item.payWay==="YsPay"?"银行卡":'/',
          memberName:item.memberName || '/',
          memberPhone:item.memberPhone || '/',
          memberAddress:item.memberAddress || '/',
          activityTypeCode:activityTypeCode,
          orderTotalPrice: Decimal(item.orderTotalPrice).div(Decimal(100)).toNumber().toFixed(2) || '/',
          orderPayPrice: Decimal(item.orderPayPrice).div(Decimal(100)).toNumber().toFixed(2) || '/',
          createTime: item.createTime || '/',
          orderState: item.orderState ==='3'?"待付款":item.orderState==='4'?"待发货":item.orderState ==='5'?"待收货":item.orderState === "6"?"待分享":item.orderState==='9'?"交易成功":item.orderState ==='0'?"交易关闭":""
        })
      })
      const option = {
        fileName: '商城订单列表',
        header: [
          {
            title: '商城订单列表',
            prop: '',
            children: [
              {
                title: '订单编号',
                prop: 'orderCode',
              },
              // {
              //   title: '所属商户',
              //   prop: 'storeName',
              // },
              {
                title: '买家昵称',
                prop: 'buyMemberName',
              },
              {
                title: '用户手机号',
                prop: 'orderMemberPhone',
              },
              {
                title: '支付方式',
                prop: 'payWay',
              },
              {
                title: '收货人',
                prop: 'memberName',
              },
              {
                title: '收货人联系方式',
                prop: 'memberPhone',
              },
              {
                title: '收货地址',
                prop: 'memberAddress',
              },
              {
                title: '订单类型',
                prop: 'activityTypeCode',

              },
              {
                title: '订单金额（元）',
                prop: 'orderTotalPrice',
                valueType: 'number'
              },
              {
                title: '实付金额（元）',
                prop: 'orderPayPrice',
                valueType: 'number'
              },
              {
                title: '订单时间',
                prop: 'createTime',
              },
              {
                title: '订单状态',
                prop: 'orderState',
              },
            ]
          },
        ],

        dataSource: data
      }
      Json2Excel(option)
    })
  }

  return (
    <div className={'wrap-box wrap-box-content'}>
      <TheQueryForm ref={queryFormRef} show={true} option={searchOption}
        onGetValues={(values) => onFormSearch(values)}
        onReset={(values) => onReset(values)}
      >
        <TheButton size="middle" haspermi={['orderManage:list:export']} onClick={() => toExport()} type="default">导出</TheButton>
      </TheQueryForm>
      <Tabs defaultActiveKey="" items={tabData} onChange={changeKey} />
      {dataSource ? <OrderTable dataSource={dataSource} getData={()=>getData({ ...pageData, orderState, ...queryForm})} ></OrderTable> : null} 
      <div style={{ textAlign: "center" }}>
        {dataSource.length !== 0 ? <Pagination current={pageData.pageNo} pageSize={pageData.pageSize} onChange={pageChange} total={total} /> : null }
      </div>
    </div>
  )
}

export default StoreBackMallOrder